package shuai.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;

public class UserTemplateDao implements UserDao {

	public static final RowMapper rowMapper=new ParameterizedRowMapper<User>() {
		public User mapRow(ResultSet rs, int rowNum) throws SQLException {
			User user=new User();
			user.setId(rs.getInt("id"));
			user.setUsername(rs.getString("username"));
			user.setPassword(rs.getString("password"));
			user.setAge(rs.getInt("age"));				
			return user;
		}
	};
	private JdbcTemplate jdbcTemplate;
	
	
	public List<User> search() {
		String sql="select * from t_user";
		/*RowMapper<User> rowMapper=new ParameterizedRowMapper<User>() {

			public User mapRow(ResultSet rs, int rowNum) throws SQLException {
				User user=new User();
				user.setId(rs.getInt("id"));
				user.setUsername(rs.getString("username"));
				user.setPassword(rs.getString("password"));
				user.setAge(rs.getInt("age"));				
				return user;
			}
		};*/
		List<User> list=jdbcTemplate.query(sql,rowMapper);
		return list;
	}
	
	//多条件查询
	public List<User> search(User user) {
		StringBuilder sBuilder=new StringBuilder("select * from t_user where 1=1");
		List pList=new ArrayList();
		if(user!=null){
			if(user.getUsername()!=null&&user.getUsername().trim().length()!=0){
				sBuilder.append(" and username like ?");
				pList.add("%"+user.getUsername()+"%");
			}
			if(user.getAge()>0){
				sBuilder.append(" and age>?");
				pList.add(user.getAge());
			}
		}
		Object[] objects=pList.toArray();
		List<User> list=jdbcTemplate.query(sBuilder.toString(),objects,rowMapper);
		return list;
	}

	public User findById(int Userno) {
		String sql="select * from t_user where id=?";
		List<User> list=jdbcTemplate.query(sql, rowMapper,Userno);
		return list.size()>0?list.get(0):null;
	}

	public void save(User user) {
		String sql="insert into t_user(username,password,age) values(?,?,?)";
		Object[] params={user.getUsername(),user.getPassword(),user.getAge()};
		jdbcTemplate.update(sql,params);
	}

	public void update(User user) {
		

	}

	public void delete(int userno) {
		

	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
	
}
